﻿using K9Nano.Domain;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;

namespace K9Nano.EfCore.MySql;

public static class K9NanoMySqlStartupExtensions
{
    public static IK9AppBuilder AddMySql<TDbContext>(this IK9AppBuilder app,
        string connectionString,
        string migrationAssemblyName,
        Action<DbContextOptionsBuilder>? optionAction = null,
        ServiceLifetime lifetime = ServiceLifetime.Scoped)
            where TDbContext : DbContext
    {
        app.Services.AddDbContext<TDbContext>(
           (dbContextOptions) =>
            {
                dbContextOptions.UseMySql(
                    connectionString,
                    ServerVersion.AutoDetect(connectionString),
                    b =>
                    {
                        b.MigrationsAssembly(migrationAssemblyName);
                    });

                optionAction?.Invoke(dbContextOptions);
            },
            lifetime
        );
        return app;
    }

    public static IK9AppBuilder AddMySqlPool<TDbContext>(this IK9AppBuilder app,
       string connectionString,
       string migrationAssemblyName,
       Action<DbContextOptionsBuilder>? optionAction = null)
           where TDbContext : DbContext
    {
        app.Services.AddDbContextPool<TDbContext>(
           (dbContextOptions) =>
           {
               dbContextOptions.UseMySql(
                   connectionString,
                   ServerVersion.AutoDetect(connectionString),
                   b =>
                   {
                       b.MigrationsAssembly(migrationAssemblyName);
                   });

               optionAction?.Invoke(dbContextOptions);
           }
        );
        return app;
    }
}
